package com.kfh.ybracelet.login;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.base.HomeActivity;
import com.kfh.ybracelet.bean.LoginResult;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;

import java.util.Set;

/**
 * 登录
 * Created by Administrator on 2015/7/20.
 */
public class LoginActivity extends BaseActivity {

    private TextView tv_forget_psw;
    private ImageView iv_delete_psw;
    private ImageView iv_delete_username;
    private EditText et_username;
    private EditText et_psw;
    private TextView tv_login;
    private Intent mIntent;
    //是否需要自动登录
    private boolean isAutoLogin;
//    private boolean isExit;//按返回键的时候是否退出app

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        isAutoLogin = getIntent().getBooleanExtra("isAutoLogin", true);
//        isExit = getIntent().getBooleanExtra("isExit", false);

        mApplication.addActivity(this);

        initWidget();

        //自动登录
        autoLogin();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        et_username.setText(sp.getString(Constant.MOBILE, ""));
        et_psw.setText("");

    }

    public void initWidget() {

        et_psw = (EditText) findViewById(R.id.et_psw);
        et_username = (EditText) findViewById(R.id.et_username);
        iv_delete_psw = (ImageView) findViewById(R.id.iv_delete_psw);
        iv_delete_username = (ImageView) findViewById(R.id.iv_delete_username);
        tv_forget_psw = (TextView) findViewById(R.id.tv_forget_psw);
        tv_login = (TextView) findViewById(R.id.tv_login);
        TextView tv_register = (TextView) findViewById(R.id.tv_register);

        iv_delete_psw.setOnClickListener(this);
        iv_delete_username.setOnClickListener(this);
        tv_forget_psw.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        tv_register.setOnClickListener(this);

        et_username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    //显示叉号
                    iv_delete_username.setVisibility(et_username.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);

                    et_username.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                            //显示叉号
                            iv_delete_username.setVisibility(et_username.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);

                        }

                        @Override
                        public void afterTextChanged(Editable editable) {
                        }
                    });

                } else {
                    iv_delete_username.setVisibility(View.INVISIBLE);

                }
            }
        });

        et_psw.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    //显示叉号
                    iv_delete_psw.setVisibility(et_psw.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);
                    et_psw.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                            //显示叉号
                            iv_delete_psw.setVisibility(et_psw.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);
                        }

                        @Override
                        public void afterTextChanged(Editable editable) {

                        }
                    });

                } else {
                    iv_delete_psw.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    private void showSoftInput(EditText editText) {

        InputMethodManager inputManager =
                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_delete_psw: //刪除密码

                et_psw.setText("");
                showSoftInput(et_psw);

                break;
            case R.id.iv_delete_username://删除手机号

                et_username.setText("");
                showSoftInput(et_username);

                break;

            case R.id.tv_forget_psw:
                //忘記密碼
                mIntent = new Intent(this, ForgetPswActivity.class);
                startActivity(mIntent);

                break;

            case R.id.tv_login:
//                登錄
//                mIntent = new Intent(this, HomeActivity.class);
//                startActivity(mIntent);
//                finish();

                if (CommonUtils.isNull(et_username.getText().toString().trim())) {
                    showToast("请输入用户名");
                    return;
                }

                if (!CommonUtils.isPhone(et_username.getText().toString().trim())) {
                    showToast("请输入正确的手机号码");
                    return;
                }

                if (CommonUtils.isNull(et_psw.getText().toString().trim())) {
                    showToast("请输入密码");
                    return;
                }

                String unEncryptpsw = et_psw.getText().toString().trim();
                //密码MD5加密
                String md5Psw = "";

                if (Constant.MINGLUXING_CODE.equals(unEncryptpsw)) {
                    //记住密码时 点击的登录
                    md5Psw = sp.getString(Constant.PSW, "");
                } else {
                    md5Psw = CommonUtils.toMd5(unEncryptpsw.getBytes());
                }

                login(et_username.getText().toString().trim(), md5Psw.toUpperCase());

                break;

            case R.id.tv_register:
                //注册
                mIntent = new Intent(this, RegisterActivity.class);
                startActivity(mIntent);

                break;

        }

    }

    private void login(final String userName, final String psw) {

        //网络不可用
        if (!CommonUtils.isNetworkAvailable(getApplicationContext())) {
            showToast(getResources().getString(R.string.net_off));
            return;
        }

        JSONObject j = new JSONObject();
        j.put("phoneNum", et_username.getText().toString().trim());
        j.put("pwd", psw);

        HttpUtil.setPostRequest("登录中...", this, Constant.WEB_ROOT + Constant.LOGIN,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

                    @TargetApi(Build.VERSION_CODES.KITKAT)
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {
                            LoginResult loginResult = JSONObject.parseObject(str, LoginResult.class);

//                    String get=sp.getString(Constant.LOGIN_PSW, "");
//                            if (loginResult.code == Constant.STATUS_SUCCESS) {
                                if (loginResult.data == null || loginResult.token == null) {
                                    showToast("登陆失败");
                                    return;
                                }

                                //防止意外退出时 切换账号后 sp中文件未清理完全
                                if (!TextUtils.isEmpty(sp.getString(Constant.MOBILE, "")) && !userName.equals(sp.getString(Constant.MOBILE, ""))) {
                                    sp.edit().clear().apply();
                                }

                                //数据存储
                                SharedPreferences.Editor edit = sp.edit();
                                edit.putString(Constant.NAME, loginResult.data.nickName);
                                edit.putString(Constant.USERIMG, loginResult.data.userImg);
                                edit.putString(Constant.NICKNAME, loginResult.data.nickName);
                                edit.putString(Constant.TOKEN, loginResult.token.token);
                                edit.putString(Constant.AGE, loginResult.data.birthDay);
//                                edit.putString(Constant.PSW, loginResult.data.pwd);
                                edit.putString(Constant.SEX, loginResult.data.sex);
                                edit.putString(Constant.BIRTHDAY, loginResult.data.birthDay);
                                edit.putString(Constant.MOBILE, loginResult.data.mobile);
                                edit.putString(Constant.USERID, loginResult.data.mobile);
//                                edit.putString(Constant.id, loginResult.data.id);
                                //记住用户名和密码
                                edit.putString(Constant.USERID, userName);
                                edit.putString(Constant.PSW, psw);

                                Object readObj = CommonUtils.readObj(Constant.REMAIND + userName);

                                if (readObj != null) {

                                    Set<String> remaind = (Set<String>) readObj;
                                    edit.putStringSet(Constant.REMAIND + userName, remaind).apply();

                                } else {
                                    Log.e("tag", " readObj 为 空 ");
                                }

//                                //保存mqtt IP
//                                edit.putString(Constant.MQTTIP, loginResult.data.mqttIp);
//                                edit.putString(Constant.MQTTPORT, loginResult.data.mqttPort);
//                                //设置系统topic
//                                Constant.SYSTEM_TOPIC = "/system/" + loginResult.data.mobile;
//                                Constant.topicMap = new HashMap<String, TopicBean>();
//                                if (loginResult.data.topicList != null && loginResult.data.topicList.size() > 0) {
//
//                                    Constant.TOPICS = new String[loginResult.data.topicList.size()];
//                                    for (int i = 0; i < loginResult.data.topicList.size(); i++) {
//                                        Constant.TOPICS[i] = loginResult.data.topicList.get(i).topic;
//                                        Constant.topicMap.put(loginResult.data.topicList.get(i).topic, loginResult.data.topicList.get(i));
//                                    }
//                                }
//                                edit.putString(Constant.TOPIC_MAP, JSON.toJSONString(Constant.topicMap, true));//保存到sp中,防止内存中的被销毁

//                                LogUtil.e("tag", "保存的topic  json : " + s);

                                edit.apply();

//                                //连接mqtt
//                                mApplication.loginMqtt();

                                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                                startActivity(intent);
//                                finish();
//                            } else {
//                                showToast(Constant.showErrorMsg(loginResult.code, LoginActivity.this));
//                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LogUtil.e("TAG", str);
                        }

                    }
                }, null);
    }

    /**
     * 自动登录
     */
    private void autoLogin() {

        String userName = sp.getString(Constant.USERID, "");
        String psw = sp.getString(Constant.PSW, "");

        if (CommonUtils.isNull(userName) || CommonUtils.isNull(psw))
            return;

        et_username.setText(userName);
        et_psw.setText(Constant.MINGLUXING_CODE);

        et_username.setSelection(userName.length());
        et_psw.setSelection(Constant.MINGLUXING_CODE.length());

        //是否自动登录
        if (isAutoLogin)
            login(userName, psw);//记住的密码为md5加密后的 所以无需再MD5加密

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        mApplication.exit();
        finish();
    }

//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//
//            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
//            View v = getCurrentFocus();
//
//            if (isShouldHideInput(v, ev)) {
//                hideSoftInput(v.getWindowToken());
//            }
//        }
//        return super.dispatchTouchEvent(ev);
//    }

//    /**
//     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
//     *
//     * @param v
//     * @param event
//     * @return
//     */
//    private boolean isShouldHideInput(View v, MotionEvent event) {
//        if (v != null && (v instanceof EditText)) {
//            int[] l = {0, 0};
//            v.getLocationInWindow(l);
//            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
//                    + v.getWidth();
//            if (event.getX() > left && event.getX() < right
//                    && event.getY() > top && event.getY() < bottom) {
//                // 点击EditText的事件，忽略它。
//                return false;
//            } else {
//                return true;
//            }
//        }
//        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
//        return false;
//    }
//
//    /**
//     * 多种隐藏软件盘方法的其中一种
//     *
//     * @param token
//     */
//    private void hideSoftInput(IBinder token) {
//        if (token != null) {
//            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            im.hideSoftInputFromWindow(token,
//                    InputMethodManager.HIDE_NOT_ALWAYS);
//        }
//    }
//
//
//    // /屏蔽按键
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        switch (keyCode) {
//            case KeyEvent.KEYCODE_MENU:
//                return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        mApplication.cancelPendingRequests(getClass().getName());
//    }
}
